import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: JSON.parse(localStorage.getItem('user') || 'null'),
    users: JSON.parse(localStorage.getItem('users') || '[]')
  }),

  getters: {
    currentUser: (state) => state.user,
    isLogin: (state) => !!state.user,
    isAdmin: (state) => state.user?.role === 'Admin',
    isExpert: (state) => state.user?.role === 'Expert'  // ✅ 新增
  },

  actions: {
    init() {
      this.user = JSON.parse(localStorage.getItem('user') || 'null')
      this.users = JSON.parse(localStorage.getItem('users') || '[]')
    },
    setUser(user: any) {
      // 字段标准化：统一为 username
      const normalizedUser = {
        ...user,
        username: user.username || user.userName
      }
      this.user = normalizedUser
      localStorage.setItem('user', JSON.stringify(normalizedUser))
    },

    addUser(user: { id: number; username: string; password: string; role: string; avatar: string; points: number; favorites: never[]; createdAt: string }) {
      this.users.push(user)
      localStorage.setItem('users', JSON.stringify(this.users))
    },

    updateUser(newData: any) {
      this.user = { ...this.user, ...newData }
      localStorage.setItem('user', JSON.stringify(this.user))
    },

    logout() {
      this.user = null
      localStorage.removeItem('user')
    }
  }

  
})
